package com.sunlake.spring.main.common.utils;
import com.sunlake.spring.main.model.auth.po.UsersPO;
import org.slf4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
* 当前用户工具类
* 用于获取当前登录用户的ID
* 务必通过这种方式获取当前用户ID，而不是直接从SecurityContextHolder中获取喵~
* @author by liuhanzhi
*/
@Component
public class CurrentUserUtil {
    private static final Logger log = LoggerUtil.getLogger(CurrentUserUtil.class);
    public static Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        System.out.println(authentication);
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }

        Object principal = authentication.getPrincipal();
        if (principal == null) {
            return null;
        }

        // 专门处理匿名用户的情况
        if (principal instanceof String && "anonymousUser".equals(principal)) {
            log.debug("当前用户是匿名用户");
            return null;
        }

        // 安全地处理不同类型的principal
        if (principal instanceof Long) {
            return (Long) principal;
        } else if (principal instanceof String) {
            try {
                return Long.parseLong((String) principal);
            } catch (NumberFormatException e) {
                log.error("无法将String类型的principal转换为Long: {}", principal);
                return null;
            }
        } else if (principal instanceof Number) {
            return ((Number) principal).longValue();
        }
        else if (principal instanceof UsersPO) {
             Integer id = ((UsersPO) principal).getId();
             return id == null ? null : id.longValue();
        }

        log.warn("未知类型的principal: {}", principal.getClass().getName());
        return null;
    }
}